package com.xsoft.navigation.activity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

/**
 * created by zhangkai on 2021/5/20
 * email: 405547628@qq.com
 * desc:
 */
@Keep
public abstract class BaseActivity<VB extends ViewBinding> extends AppCompatActivity {
    protected VB binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = getBinding();
        if (binding != null) {
            setContentView(binding.getRoot());
            initView();
            initData();
        }
    }

    protected abstract void initView();

    protected abstract void initData();

    private VB getBinding() {
        try {
            Type genType = getClass().getGenericSuperclass();
            Type[] param = ((ParameterizedType) genType).getActualTypeArguments();
            Class<VB> vbClass = (Class<VB>) param[0];
            Method inflate = vbClass.getMethod("inflate", LayoutInflater.class);
            return (VB) inflate.invoke(null, getLayoutInflater());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
